package cn.com.sise.servlet;
import cn.com.sise.entity.Admin;
import cn.com.sise.service.IAdminService;
import cn.com.sise.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 得到提交的验证码
        String randStrInput=request.getParameter("randStr");

        // 获取session中的验证码
        String randStr= (String) request.getSession().getAttribute("randStr");

		// 判断用户输入的验证码是否正确，若不正确，则页面重定向到login.jsp页面
        if (!randStrInput.trim().equals(randStr)) {
            response.sendRedirect("login.jsp");
        }

        //否则执行下面的操作
            IAdminService adminService=new AdminServiceImpl();
            Admin admin=new Admin();
            admin.setAccount(request.getParameter("account"));
            admin.setPassword(request.getParameter("password"));
            Admin result;
            try {
                result = adminService.login(admin);
                if (result!=null) {  //存储 登录用户信息
                    request.getSession().setAttribute("user", admin);
                    response.sendRedirect("showAllBooksServlet");
                }else {
                    response.sendRedirect("login.jsp");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
